import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

let cart = JSON.parse(localStorage.getItem('cart') || '[]');
const store = new Vuex.Store({
  state: {
    cart
  },
  mutations: {
    addToCart(state, goodsinfo) {
      let a = state.cart.find(c => c.id == goodsinfo.id);
      if (a) {
        a.count += parseInt(goodsinfo.count);
      } else {
        state.cart.push(goodsinfo);
      }
      localStorage.setItem('cart', JSON.stringify(state.cart));
    },
    updateGoods(state, goodsinfo) {
      let a = state.cart.find(c => c.id == goodsinfo.id);
      a.count = parseInt(goodsinfo.count);
      localStorage.setItem('cart', JSON.stringify(state.cart));
    },
    removeGoods(state, id) {
      let index = state.cart.findIndex(c => c.id == id);
      state.cart.splice(index, 1);
      localStorage.setItem('cart', JSON.stringify(state.cart));
    },
    updataGoodsSelecter(state, obj) {
      let a = state.cart.find(c => c.id == obj.id);
      a.selected = obj.selected;
      localStorage.setItem('cart', JSON.stringify(state.cart));
    }
  },
  getters: {
    getAllCount(state) {
      let c = 0;
      state.cart.forEach(el => {
        c += el.count;
      });
      return c;
    },
    getGoodsCount(state) {
      let obj = {};
      state.cart.forEach(el => {
        obj[el.id] = el.count;
      });
      return obj;
    },
    getGoodsSelected(state) {
      let obj = {};
      state.cart.forEach(el => {
        obj[el.id] = el.selected;
      });
      return obj;
    },
    getGoodsCountAndAmount(state) {
      let obj = { count: 0, amount: 0 };
      state.cart.forEach(el => {
        if (el.selected) {
          obj.count += el.count;
          obj.amount += el.price * el.count;
        }
      });
      return obj;
    }
  }
});

export default store;
